package com.wjbgn.bsolver.server.util;

import com.alibaba.fastjson.JSONObject;
import com.wjbgn.bsolver.server.api.UserClient;
import com.wjbgn.bsolver.server.dto.UserDTO;
import com.wjbgn.stater.dto.Result;
import com.wjbgn.stater.enums.CommonReturnEnum;
import com.wjbgn.stater.util.redis.RedisUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 用户信息缓存工具类
 *
 * @author wjbgn
 * @date 2022/05/17 09:25
 **/
@Component
public class UserInfoCacheUtil {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserClient userClient;

    /**
     * 根据username获取id
     *
     * @param username
     * @return java.lang.String
     * @author weirx
     * @date: 2022/5/16
     */
    public long getUserIdByUsername(String username) {
        Long str = null;
        String userStr = redisUtil.getString("userInfo:" + username);
        if (StringUtils.isEmpty(userStr)) {
            Result userByUsername = userClient.getUserByUsername(username);
            if (userByUsername.getCode() == CommonReturnEnum.SUCCESS.getCode()) {
                UserDTO user = JSONObject.parseObject(JSONObject.toJSONString(userByUsername.getData())).toJavaObject(UserDTO.class);
                user.setPassword(null);
                redisUtil.setObject("userInfo:" + username, user);
                str = user.getId();
            }
        } else {
            UserDTO userDTO = JSONObject.parseObject(userStr).toJavaObject(UserDTO.class);
            str = userDTO == null ? null : userDTO.getId();
        }
        return str;
    }

    /**
     * 根据username获取id
     *
     * @param username
     * @return java.lang.String
     * @author weirx
     * @date: 2022/5/16
     */
    public String getUserNicknameByUsername(String username) {
        String str = null;
        String userStr = redisUtil.getString("userInfo:" + username);
        if (StringUtils.isEmpty(userStr)) {
            Result userByUsername = userClient.getUserByUsername(username);
            if (userByUsername.getCode() == CommonReturnEnum.SUCCESS.getCode()) {
                UserDTO user = JSONObject.parseObject(JSONObject.toJSONString(userByUsername.getData())).toJavaObject(UserDTO.class);
                user.setPassword(null);
                redisUtil.setObject("userInfo:" + username, user);
                str = user.getNickname();
            }
        } else {
            UserDTO userDTO = JSONObject.parseObject(userStr).toJavaObject(UserDTO.class);
            str = userDTO == null ? null : userDTO.getNickname();
        }
        return str;
    }
}
